/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.filterX;

//import acceso.aplicacion.Bulldozer;
import acceso.util.LogueoHelper;
import acceso.util.UserSesion;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wf3.core.Configuration;

/**
 *
 * @author john
 */
public class CookieFilter implements Filter {

    private FilterConfig filterConfig = null;
    public static String cookie_name = "";

    public CookieFilter() {
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            System.out.println("[Cookie Filter]");
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession ses = req.getSession();

            Cookie cookie = null;
            Cookie[] cookies = req.getCookies();
            try {
                if (cookies != null && cookies.length > 0) {
                    for (Cookie ck : cookies) {
                        if (ck.getName().contentEquals(cookie_name) && !ck.getValue().isEmpty()) {
                            cookie = ck;
                            break;
                        }
                    }
                }
            } catch (Exception ep) {
                System.out.println(">>" + ep.getMessage());
                ep.printStackTrace();
            }

            if (cookie != null) {
//                System.out.println("[Cookie filter]Existe cookie");
//                System.out.println("cookie name: " + cookie.getName());
//                System.out.println("cookie value: " + cookie.getValue());
//                System.out.println("cookie path: " + cookie.getPath());
//                System.out.println("cookie expire: " + cookie.getMaxAge());

//                if (ses.getAttribute("sesion") != null) {//ELiMINAR!!
                if (ses.getAttribute("US") != null) {
//                    System.out.println("[Cookie filter]Existe sesion");
                    //tienes cookie y sesion, sigue nomas
                    if (Integer.parseInt(cookie.getValue()) == ((UserSesion) ses.getAttribute("US")).getId_sesion()) {
//                        System.out.println("[Cookie filter]Validacion correcta, pasa nomas");
                        chain.doFilter(request, response);
                    } else {
//                        System.out.println("[Cookie filter]Cokkie != UserSesion");
//                        System.out.println("[Cookie filter]Invalidadno sesion");
                        ses.invalidate();
                        System.out.println("[Cookie filter]Tratando de loguear con la cookkie");
                        boolean r = LogueoHelper.loguear(req, Long.parseLong(cookie.getValue()));
                        if (r) {
//                            System.out.println("[Cookie filter]Logueo succesful");
                            chain.doFilter(request, response);
                        } else {
//                            System.out.println("[Cookie filter]No se logueo, eliminando todo. ID_SESION: " + Long.parseLong(cookie.getValue()));
                            ses.invalidate();
//                            Cookie cookie2 = new Cookie(((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name(), Long.parseLong(cookie.getValue()) + "");
//                            System.out.println("Cookie name: " + ((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name());
//                            System.out.println("Cookie value: " + Long.parseLong(cookie.getValue()));
//                            cookie2.setPath(cookie.getPath()+"");
//                            cookie2.setDomain(cookie.getDomain()+"");
//                            System.out.println("Cookie domain: " + ((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_cookie_domain());
//                            cookie2.setMaxAge(0);
//                            
//                            res.addCookie(cookie2);
////                            res.sendRedirect("/");
//                            res.sendRedirect(req.getContextPath() + "/workflow2/eliminarcookie.jsp?url=/");

//                            Cookie cookie2 = new Cookie(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name(), "");
//                            for (int i = 0; i < cookies.length; i++) {
//                                if (cookies[i].getName().equals(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name())) {
//                                    cookie2.setComment(cookies[i].getComment());
//                                    cookie2.setDomain(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_cookie_domain());
//                                    cookie2.setPath("/");
//                                    cookie2.setSecure(cookies[i].getSecure());
//                                    cookie2.setVersion(cookies[i].getVersion());
//                                    cookie2.setMaxAge(0);
//                                    System.out.println("[cookie filter]cookie modificado: " + cookie2.getMaxAge());
//                                    res.addCookie(cookie2);
//                                }
//                            }
//                            res.sendRedirect("/");
                            RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                            dispatcher.forward(req, res);
                        }
                    }
                } else {
//                    System.out.println("[Cookie filter]no hay sesion");
                    //tienes cookie pero no sesion, logueo automatico
                    System.out.println("[Cookie filter]Tratando de loguear con la cookkie");
                    boolean r = LogueoHelper.loguear(req, Long.parseLong(cookie.getValue()));
                    if (r) {
//                        System.out.println("[Cookie filter]Logueo succesful");
                        chain.doFilter(request, response);
                    } else {
//                        System.out.println("[Cookie filter]No se logueo, eliminando todo. ID_SESION: " + Long.parseLong(cookie.getValue()));
//                        if (ses.getAttribute("sesion") != null) {
//                            ses.invalidate();
//                        }
//                        Cookie cookie2 = new Cookie(((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name(), Long.parseLong(cookie.getValue()) + "");
//                        System.out.println("Cookie name: " + ((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name());
//                        System.out.println("Cookie value: " + Long.parseLong(cookie.getValue()));
//                        cookie2.setPath(cookie.getPath() + "");
//                        cookie2.setDomain(cookie.getDomain() + "");
//                        System.out.println("Cookie domain: " + ((Bulldozer) req.getSession().getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_cookie_domain());
//                        cookie2.setMaxAge(0);
//
//                        res.addCookie(cookie2);
////                        res.sendRedirect("/");
//                        res.sendRedirect(req.getContextPath() + "/workflow2/eliminarcookie.jsp?url=" + req.getContextPath());

//                        Cookie cookie2 = new Cookie(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name(), "");
//                        for (int i = 0; i < cookies.length; i++) {
//                            if (cookies[i].getName().equals(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getCookie_name())) {
//                                cookie2.setComment(cookies[i].getComment());
//                                cookie2.setDomain(((Bulldozer) ses.getServletContext().getAttribute("acceso")).getWorkflow().getMaster_login_cookie_domain());
//                                cookie2.setPath("/");
//                                cookie2.setSecure(cookies[i].getSecure());
//                                cookie2.setVersion(cookies[i].getVersion());
//                                cookie2.setMaxAge(0);
//                                System.out.println("[cookie filter]cookie modificado: " + cookie2.getMaxAge());
//                                res.addCookie(cookie2);
//                            }
//                        }
//                        res.sendRedirect("/");
                        RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                        dispatcher.forward(req, res);
                    }
                }
            } else {
                System.out.println("[Cookie filter]No hay cookie");
//                if (ses.getAttribute("sesion") != null) {//ELIMiNAR!!!
                if (ses.getAttribute("US") != null) {
                    System.out.println("[Cookie filter]Hay sesion. DESTRUIR");
                    //no tienes cookie pero si sesion, destruir sesion
                    ses.invalidate();
                    RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                    dispatcher.forward(req, res);
                } else {
//                    System.out.println("[Cookie filter]no hay sesion");
                    //no tienes cookie ni sesion, logueate
                    RequestDispatcher dispatcher = req.getRequestDispatcher("/");
                    dispatcher.forward(req, res);
                }
            }
        } catch (IOException | ServletException | NumberFormatException ex) {
            System.out.println("[CoockieFilter]Ex: " + ex);
            ex.printStackTrace();
        }
    }

    /**
     * Return the filter configuration object for this filter.
     *
     * @return
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter
     */
    @Override
    public void destroy() {
    }

    /**
     * Init method for this filter
     */
    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        cookie_name = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).getCookie_name();
        System.out.println("[Cookie filter: configurado][cookie_name:" + cookie_name + "]");
    }

    public synchronized static void update_filter(String cn) {
        cookie_name = cn;
        System.out.println("[Cookie filter: actualizado][cookie_name:" + cookie_name + "]");
    }
}
